<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row shadow="hover" v-show="showSearch" class="ml10">
				<el-form :model="queryParams" ref="queryRef" :inline="true" @keyup.enter="handleQuery">
					<el-form-item label="发起人" prop="adminList">
						<select-show v-model:orgList="queryParams.adminList"></select-show>
					</el-form-item>
					<!-- <el-form-item label="分组名" prop="groupName">

						<el-select style="width: 100%" v-model="queryParams.groupName" placeholder="请选择分组名">
							<el-option v-for="option in groupArr" :key="option.value" :label="option.groupName"
								:value="option.groupName"></el-option>
						</el-select>
					</el-form-item> -->
					<el-form-item label="部门" prop="deptList">
						<select-show v-model:orgList="queryParams.deptList" type="dept" click1="1"
							@update:type="settype"></select-show>
					</el-form-item>
					<el-form-item label="状态" prop="status">
						<el-select style="width: 100%" v-model="queryParams.status" placeholder="请选择状态">
							<el-option :key="1" label="进行中" :value="1" />
							<el-option :key="2" label="已结束" :value="2" />
						</el-select>
					</el-form-item>
					<el-form-item label="业务时间" prop="businessTime">
						<el-date-picker type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" v-model="queryParams.businessTime"
							is-range range-separator="To" />
					</el-form-item>
					<!-- <el-form-item label="发起时间" prop="taskTime">
						<el-date-picker type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" v-model="queryParams.taskTime"
							is-range range-separator="To" />
					</el-form-item> -->
					<!-- <el-form-item label="完成时间" prop="endTime">
						<el-date-picker type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" v-model="queryParams.endTime"
							is-range range-separator="To" />
					</el-form-item> -->
					<el-form-item>
						<el-button icon="search" type="primary" @click="handleQuery">
							{{ $t('common.queryBtn') }}
						</el-button>
						<el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
						<el-button type="primary" :disabled="isdisabled == 1" @click="downloadTask">导出</el-button>
						<el-button type="primary" :disabled="isdisabled == 1" @click="downloadSelectedTasks">导出选中</el-button>
					</el-form-item>
				</el-form>
			</el-row>

			<el-row>
				<div class="mb8" style="width: 100%">
					<right-toolbar v-model:showSearch="showSearch" class="ml10" style="float: right; margin-right: 20px"
						@queryTable="handleQuery"></right-toolbar>
				</div>
			</el-row>

			<el-table ref="dataTableRef" v-loading="loading" :data="dataList" highlight-current-row border
				:cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle">
				<el-table-column type="selection" width="40" align="center" />
				<el-table-column label="分组" prop="groupName" width="100" />
				<el-table-column label="流程" prop="name" width="150" />
				<el-table-column label="发起人" prop="displayName" width="150" />
				<el-table-column label="发起时间" prop="createTime" width="200" />
				<el-table-column label="结束时间" prop="endTime" width="200" />
				<el-table-column label="状态" prop="taskCreateTime" width="100">
					<template #default="scope">
						<el-tag v-if="scope.row.status == 1" type="success">进行中</el-tag>
						<el-tag v-else-if="scope.row.status == 2 && scope.row.subStatus == 2" type="error">已拒绝</el-tag>
						<el-tag v-else-if="scope.row.status == 2 && scope.row.subStatus == 3" type="error">已撤销</el-tag>
						<el-tag v-else>已结束</el-tag>
					</template>
				</el-table-column>

				<el-table-column fixed="right" label="操作">
					<template #default="scope">
						<el-button type="primary" size="small" link icon="View" @click="deal(scope.row)"> 查看 </el-button>
						<el-popconfirm title="确认终止吗?" @confirm="stop(scope.row)">
							<template #reference>
								<el-button :disabled="scope.row.status != 1" type="primary" size="small" link icon="VideoPause"> 终止流程
								</el-button>
							</template>
						</el-popconfirm>
						<!-- <el-button type="primary" size="small" link icon="View" @click="deal(scope.row)">加签</el-button> -->
						<!--						<el-button v-if="scope.row.status != 1" type="primary" size="small" link icon="VideoPause" @click="recreate(scope.row)">-->
						<!--							重新发起-->
						<!--						</el-button>-->
					</template>
				</el-table-column>
			</el-table>

			<pagination v-if="total > 0" :total="total" :current="queryParams.pageNum" :size="queryParams.pageSize"
				@sizeChange="sizeChange" @currentChange="currentChange" />
			<!--			右侧抽屉-->
			<el-drawer v-model="rightDrawerVisible" direction="rtl" size="445px">
				<template #header>
					<h3>{{ currentData?.name }}</h3>
				</template>
				<template #default>
					<el-card class="box-card">
						<form-render ref="formRenderRef" :form-list="currentOpenFlowForm"></form-render>
					</el-card>
					<flow-node-format :disableSelect="true" :formData="formValue"
						:processInstanceId="currentData.processInstanceId" :flow-id="currentData.flowId"
						ref="flowNodeFormatRef"></flow-node-format>
				</template>
			</el-drawer>
		</div>
	</div>
</template>
<script setup lang="ts">
import FormRender from '/@/views/flow/form/render/FormRender.vue';
import FlowNodeFormat from '/@/views/flow/form/tools/FlowNodeFormatData.vue';
import { downloadSelected, stopProcessInstance, recreateProcessInstance, queryTaskList, downloadTaskList, processGroupList } from '/@/api/flow/task';
import { detail } from '/@/api/flow/processInstance';
import { BasicTableProps, useTable } from '/@/hooks/table';
import selectShow from '/@/components/OrgSelector/choose.vue';
import * as XLSX from "xlsx";

const state: BasicTableProps = reactive<BasicTableProps>({});
const { tableStyle } = useTable(state);
const rightDrawerVisible = ref(false);

const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const queryRef = ref();
// 多选变量
const selectObjs = ref([]) as any;
const groupArr = ref([]);
const multiple = ref(true);
const isdisabled = ref(0)

function stop(row) {
	stopProcessInstance({
		processInstanceId: row.processInstanceId,
	}).then((res) => {
		handleQuery();
	});
}

function recreate(row) {
	recreateProcessInstance({
		processInstanceId: row.processInstanceId,
	}).then((res) => {
		handleQuery();
	});
}
const queryParams = reactive({
	pageNum: 1,
	pageSize: 10,
	taskTime: undefined,
	endTime: undefined,
	status: 2,
	process: 1,
	groupName: '请假',
	userId: undefined,
	adminList: [],
	deptList: [],
	businessTime: undefined,
	pkOfDept: '',
	uid: '',
});

const dataList = ref();

const currentData = ref();
/**
 * 点击开始处理
 * @param row
 */
const deal = (row) => {
	currentData.value = row;
	detail({
		processInstanceId: row.processInstanceId,
	}).then((res) => {
		currentOpenFlowForm.value = res.data.formItems;
		rightDrawerVisible.value = true;
	});
};
const currentOpenFlowForm = ref();

/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	queryParams.pkOfDept = queryParams.deptList[queryParams.deptList.length - 1]?.id
	if (queryParams.adminList != null && queryParams.adminList.length > 0) {
		queryParams.userId = Number(queryParams.adminList[0].id)
	} else {
		queryParams.userId = undefined
	}
	queryTaskList(queryParams)
		.then(({ data }) => {
			console.log(data)
			// let formData = JSON.parse(data.records.formData)
			data.records.forEach((item) => {
				if (item.status == 1) {
					isdisabled.value = item.status
					return
				}
				isdisabled.value = item.status
			})

			for (const key in data.records) {
				let formData = JSON.parse(data.records[key].formData)
				data.records[key].displayName = formData.root[0].displayName
			}
			console.log(data.records);
			dataList.value = data.records;

			total.value = data.total;
		})
		.finally(() => {
			loading.value = false;
		});
}
function downloadTask() {
	//获取json并保存为Excel文件
	loading.value = true;
	downloadTaskList(queryParams)
		.then(({ data }) => {
			// 创建一个新的工作簿
			const workbook = XLSX.utils.book_new();
			// 创建一个新的工作表
			const worksheet = XLSX.utils.json_to_sheet(data);
			// 将工作表附加到工作簿，并将工作表命名为students
			XLSX.utils.book_append_sheet(workbook, worksheet, "任务");
			// 导出工作簿，并命名导出文件名为Presidents.xlsx
			XLSX.writeFile(workbook, "导出的任务列表.xlsx");
		})
		.finally(() => {
			loading.value = false;
		});
}
function downloadSelectedTasks() {
	//获取json并保存为Excel文件
	loading.value = true;
	let ids = selectObjs.value
	downloadSelected(ids)
		.then(({ data }) => {
			// 创建一个新的工作簿
			const workbook = XLSX.utils.book_new();
			// 创建一个新的工作表
			const worksheet = XLSX.utils.json_to_sheet(data);
			// 将工作表附加到工作簿，并将工作表命名为students
			XLSX.utils.book_append_sheet(workbook, worksheet, "任务");
			// 导出工作簿，并命名导出文件名为Presidents.xlsx
			XLSX.writeFile(workbook, "选中的任务列表.xlsx");
		})
		.finally(() => {
			loading.value = false;
		});
}
// 清空搜索条件
const resetQuery = () => {
	queryRef.value.resetFields();
	handleQuery();
};
function groupList() {
	processGroupList({}).then(({ data }) => {
		console.log(data)
		groupArr.value = data
	})
}
onMounted(() => {
	handleQuery();
	groupList()
});

const formValue = computed(() => {
	var obj = {};

	for (var item of currentOpenFlowForm.value) {
		obj[item.id] = item.props.value;
	}
	return obj;
});
const sizeChange = (e: any) => {
	queryParams.pageNum = 1;
	queryParams.pageSize = e;
	handleQuery();
};
const currentChange = (e: any) => {
	queryParams.pageNum = e;
	handleQuery();
};
// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	console.log("selectionChangHandle:" + objs)
	isdisabled.value = objs[0]?.status
	console.log(isdisabled.value)
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};
</script>
